{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "ff633e36",
   "metadata": {},
   "source": [
    "# 第五点五讲 Python中使用注释的规则"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "30e1eb0d",
   "metadata": {},
   "source": [
    "## 1. 什么是注释？\n",
    "\n",
    "### 1.1 注释的定义\n",
    "\n",
    "**注释（Comment）** 是在代码中添加的说明文字，用于解释代码的功能、逻辑或用途。注释不会被Python解释器执行，仅供人类阅读。\n",
    "\n",
    "### 1.2 注释的作用\n",
    "\n",
    "1. **解释代码功能**：说明代码做什么\n",
    "2. **记录设计思路**：解释为什么这样写\n",
    "3. **提供使用说明**：如何使用函数或类\n",
    "4. **标记待办事项**：记录需要完善的地方\n",
    "5. **提高可读性**：让代码更容易理解"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "52aa0f24",
   "metadata": {},
   "source": [
    "## 2. Python注释的语法\n",
    "\n",
    "### 2.1 单行注释\n",
    "\n",
    "#### (1) 基本语法\n",
    "\n",
    "```python\n",
    "# 这是一个单行注释\n",
    "```\n",
    "\n",
    "#### (2) 语法要点\n",
    "\n",
    "- 使用 `#` 符号开始\n",
    "- `#` 后面通常跟一个空格\n",
    "- 从 `#` 开始到行尾的所有内容都是注释"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "45e05e0b",
   "metadata": {},
   "source": [
    "### 2.2 行内注释\n",
    "\n",
    "#### (1) 语法格式\n",
    "\n",
    "```python\n",
    "代码语句  # 注释内容\n",
    "```\n",
    "\n",
    "#### (2) 注意事项\n",
    "\n",
    "- 代码和 `#` 之间至少要有两个空格\n",
    "- 注释要简洁明了\n",
    "- 不要重复显而易见的内容"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "85705de5",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello, World!\n",
      "结果是: 8\n"
     ]
    }
   ],
   "source": [
    "# 这是一个简单的Python程序\n",
    "print(\"Hello, World!\")  # 输出问候语\n",
    "\n",
    "# 计算两个数的和\n",
    "a = 5  # 第一个数\n",
    "b = 3  # 第二个数\n",
    "sum_result = a + b  # 计算和\n",
    "print(f\"结果是: {sum_result}\")  # 显示结果"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d4ef00a2",
   "metadata": {},
   "source": [
    "### 2.3 多行注释"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ba75cdd1",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 方法1：使用多个单行注释\n",
    "# 这是一个多行注释\n",
    "# 可以跨越多行\n",
    "# 每个注释行都以 # 开头\n",
    "# 注释内容可以是任意文本 \n",
    "def complex_function():\n",
    "    pass   "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "78887d4a",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 方法2：使用三引号（文档字符串）\n",
    "\"\"\"\n",
    "这是一个多行注释\n",
    "可以跨越多行\n",
    "通常用于函数、类或模块的文档\n",
    "\"\"\"\n",
    "\n",
    "def example_function():\n",
    "    \"\"\"\n",
    "    这是函数的文档字符串\n",
    "    解释函数的功能和用法\n",
    "    \"\"\"\n",
    "    pass"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f907afea",
   "metadata": {},
   "source": [
    "## 3. 注释的分类和用途"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "59919230",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. 解释性注释\n",
    "# 使用冒泡排序算法对列表进行排序\n",
    "def bubble_sort(arr):\n",
    "    n = len(arr)\n",
    "    # 外层循环控制排序轮数\n",
    "    for i in range(n):\n",
    "        # 内层循环进行相邻元素比较\n",
    "        for j in range(0, n - i - 1):\n",
    "            # 如果前一个元素大于后一个元素，则交换\n",
    "            if arr[j] > arr[j + 1]:\n",
    "                arr[j], arr[j + 1] = arr[j + 1], arr[j]\n",
    "    return arr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b89ba567",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 2. 文档注释（Docstring）\n",
    "def calculate_area(length, width):\n",
    "    \"\"\"\n",
    "    计算矩形的面积\n",
    "    \n",
    "    参数:\n",
    "        length (float): 矩形的长度\n",
    "        width (float): 矩形的宽度\n",
    "    \n",
    "    返回:\n",
    "        float: 矩形的面积\n",
    "    \n",
    "    示例:\n",
    "        >>> calculate_area(5, 3)\n",
    "        15\n",
    "    \"\"\"\n",
    "    return length * width\n",
    "\n",
    "class Calculator:\n",
    "    \"\"\"\n",
    "    简单的计算器类\n",
    "    \n",
    "    这个类提供基本的数学运算功能，包括加法、减法、乘法和除法。\n",
    "    \n",
    "    属性:\n",
    "        history (list): 存储计算历史记录\n",
    "    \"\"\"\n",
    "    \n",
    "    def __init__(self):\n",
    "        \"\"\"初始化计算器\"\"\"\n",
    "        self.history = []\n",
    "    \n",
    "    def add(self, a, b):\n",
    "        \"\"\"\n",
    "        执行加法运算\n",
    "        \n",
    "        参数:\n",
    "            a (float): 第一个数\n",
    "            b (float): 第二个数\n",
    "        \n",
    "        返回:\n",
    "            float: 两数之和\n",
    "        \"\"\"\n",
    "        result = a + b\n",
    "        self.history.append(f\"{a} + {b} = {result}\")\n",
    "        return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "21111473",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 3. TODO注释\n",
    "def process_data(data):\n",
    "    \"\"\"处理数据的函数\"\"\"\n",
    "    # TODO: 添加数据验证\n",
    "    # FIXME: 处理空数据的情况\n",
    "    # HACK: 临时解决方案，需要重构\n",
    "    # NOTE: 这个函数需要优化性能\n",
    "    \n",
    "    processed_data = []\n",
    "    for item in data:\n",
    "        # TODO: 实现更复杂的处理逻辑\n",
    "        processed_data.append(item.upper())\n",
    "    \n",
    "    return processed_data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e7ec5af1",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 4. 调试注释\n",
    "def debug_function(x, y):\n",
    "    \"\"\"带调试信息的函数\"\"\"\n",
    "    print(f\"DEBUG: 输入参数 x={x}, y={y}\")  # 调试输出\n",
    "    \n",
    "    result = x * y\n",
    "    print(f\"DEBUG: 计算结果 {result}\")  # 调试输出\n",
    "    \n",
    "    # 临时禁用的代码\n",
    "    # if result > 100:\n",
    "    #     print(\"结果很大\")\n",
    "    \n",
    "    return result"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4810c068",
   "metadata": {},
   "source": [
    "## 4. 注释的最佳实践\n",
    "### 4.1 何时写注释"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ca47d5ab",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 应该写注释的情况\n",
    "\n",
    "# 复杂的算法逻辑\n",
    "def quicksort(arr):\n",
    "    \"\"\"快速排序实现\"\"\"\n",
    "    if len(arr) <= 1:\n",
    "        return arr\n",
    "    \n",
    "    # 选择基准元素（通常选择中间元素）\n",
    "    pivot = arr[len(arr) // 2]\n",
    "    \n",
    "    # 分割数组：小于基准的、等于基准的、大于基准的\n",
    "    left = [x for x in arr if x < pivot]\n",
    "    middle = [x for x in arr if x == pivot]\n",
    "    right = [x for x in arr if x > pivot]\n",
    "    \n",
    "    # 递归排序并合并结果\n",
    "    return quicksort(left) + middle + quicksort(right)\n",
    "\n",
    "# 业务逻辑说明\n",
    "def calculate_discount(price, customer_type, quantity):\n",
    "    \"\"\"根据客户类型和购买数量计算折扣\"\"\"\n",
    "    base_discount = 0\n",
    "    \n",
    "    # VIP客户享受基础5%折扣\n",
    "    if customer_type == \"VIP\":\n",
    "        base_discount = 0.05\n",
    "    \n",
    "    # 批量购买额外折扣\n",
    "    if quantity >= 100:\n",
    "        base_discount += 0.1  # 额外10%折扣\n",
    "    elif quantity >= 50:\n",
    "        base_discount += 0.05  # 额外5%折扣\n",
    "    \n",
    "    return price * (1 - base_discount)\n",
    "\n",
    "# 配置和常量说明\n",
    "MAX_RETRY_ATTEMPTS = 3  # 最大重试次数\n",
    "CONNECTION_TIMEOUT = 30  # 连接超时时间（秒）\n",
    "DEFAULT_ENCODING = 'utf-8'  # 默认字符编码"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6a3c446d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 不应该写注释的情况\n",
    "\n",
    "# 不好的注释示例（过于显而易见）\n",
    "x = 5  # 将x设置为5\n",
    "y = x + 1  # y等于x加1\n",
    "print(y)  # 打印y的值\n",
    "\n",
    "# 更好的写法（不需要注释）\n",
    "counter = 5\n",
    "next_value = counter + 1\n",
    "print(next_value)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "47828ad1",
   "metadata": {},
   "source": [
    "### 4.2 注释的质量标准"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8d66082a",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 高质量注释的特征\n",
    "\n",
    "class UserManager:\n",
    "    \"\"\"\n",
    "    用户管理器类\n",
    "    \n",
    "    负责处理用户的注册、登录、权限验证等核心功能。\n",
    "    使用单例模式确保全局只有一个用户管理器实例。\n",
    "    \"\"\"\n",
    "    \n",
    "    def __init__(self):\n",
    "        \"\"\"初始化用户管理器\"\"\"\n",
    "        self._users = {}\n",
    "        self._current_user = None\n",
    "    \n",
    "    def register_user(self, username, password, email):\n",
    "        \"\"\"\n",
    "        注册新用户\n",
    "        \n",
    "        参数:\n",
    "            username (str): 用户名，长度3-20字符，只能包含字母数字下划线\n",
    "            password (str): 密码，长度至少8字符\n",
    "            email (str): 邮箱地址，必须符合邮箱格式\n",
    "        \n",
    "        返回:\n",
    "            bool: 注册成功返回True，失败返回False\n",
    "        \n",
    "        异常:\n",
    "            ValueError: 当参数不符合要求时抛出\n",
    "            UserExistsError: 当用户名已存在时抛出\n",
    "        \"\"\"\n",
    "        # 验证用户名格式\n",
    "        if not self._validate_username(username):\n",
    "            raise ValueError(\"用户名格式不正确\")\n",
    "        \n",
    "        # 检查用户是否已存在\n",
    "        if username in self._users:\n",
    "            raise UserExistsError(f\"用户 {username} 已存在\")\n",
    "        \n",
    "        # 验证密码强度\n",
    "        if not self._validate_password(password):\n",
    "            raise ValueError(\"密码强度不足\")\n",
    "        \n",
    "        # 创建用户记录\n",
    "        self._users[username] = {\n",
    "            'password': self._hash_password(password),\n",
    "            'email': email,\n",
    "            'created_at': datetime.now(),\n",
    "            'is_active': True\n",
    "        }\n",
    "        \n",
    "        return True"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "806823ea",
   "metadata": {},
   "source": [
    "### 4.3 注释的维护"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8d5ec7dc",
   "metadata": {},
   "outputs": [],
   "source": [
    "def process_order(order_data):\n",
    "    \"\"\"\n",
    "    处理订单数据\n",
    "    \n",
    "    更新历史:\n",
    "        2024-01-15: 初始版本\n",
    "        2024-02-01: 添加库存检查\n",
    "        2024-02-15: 优化性能，添加缓存机制\n",
    "    \"\"\"\n",
    "    \n",
    "    # 验证订单数据格式\n",
    "    if not validate_order_format(order_data):\n",
    "        raise ValueError(\"订单数据格式错误\")\n",
    "    \n",
    "    # 检查商品库存（2024-02-01 添加）\n",
    "    for item in order_data['items']:\n",
    "        if not check_inventory(item['product_id'], item['quantity']):\n",
    "            raise InsufficientStockError(f\"商品 {item['product_id']} 库存不足\")\n",
    "    \n",
    "    # 计算订单总金额\n",
    "    total_amount = calculate_total(order_data['items'])\n",
    "    \n",
    "    # 应用优惠券折扣\n",
    "    if 'coupon_code' in order_data:\n",
    "        discount = apply_coupon(order_data['coupon_code'], total_amount)\n",
    "        total_amount -= discount\n",
    "    \n",
    "    # 创建订单记录\n",
    "    order_id = create_order_record(order_data, total_amount)\n",
    "    \n",
    "    return order_id"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "eb98d3e7",
   "metadata": {},
   "source": [
    "## 5. 特殊注释类型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3bb92c53",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. 类型提示注释（Python 3.5+）\n",
    "\n",
    "from typing import List, Dict, Optional, Union\n",
    "\n",
    "def process_user_data(\n",
    "    users: List[Dict[str, Union[str, int]]], \n",
    "    filter_active: bool = True\n",
    ") -> List[Dict[str, Union[str, int]]]:\n",
    "    \"\"\"\n",
    "    处理用户数据列表\n",
    "    \n",
    "    参数:\n",
    "        users: 用户数据列表，每个用户包含姓名、年龄等信息\n",
    "        filter_active: 是否只返回活跃用户\n",
    "    \n",
    "    返回:\n",
    "        处理后的用户数据列表\n",
    "    \"\"\"\n",
    "    result = []\n",
    "    for user in users:\n",
    "        if filter_active and not user.get('is_active', False):\n",
    "            continue\n",
    "        result.append(user)\n",
    "    return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f40c3533",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 2. 编码声明注释\n",
    "# -*- coding: utf-8 -*-\n",
    "\"\"\"\n",
    "文件编码声明示例\n",
    "这个注释告诉Python解释器使用UTF-8编码读取文件\n",
    "\"\"\"\n",
    "\n",
    "# 或者使用更简洁的形式\n",
    "# coding: utf-8"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5d7b23a8",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 3. Shebang注释\n",
    "\n",
    "#!/usr/bin/env python3\n",
    "\"\"\"\n",
    "Shebang行，告诉系统使用哪个解释器执行脚本\n",
    "在Unix/Linux系统中，可以直接执行脚本文件\n",
    "\"\"\"\n",
    "\n",
    "print(\"Hello, World!\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f71981d2",
   "metadata": {},
   "source": [
    "## 6. 注释工具和技巧"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e9c5a6bc",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. 使用IDE的注释功能\n",
    "# 大多数IDE支持快捷键快速注释/取消注释\n",
    "# Ctrl+/ (Windows/Linux) 或 Cmd+/ (Mac)\n",
    "\n",
    "def example_function():\n",
    "    # 选中多行代码，按快捷键可以批量注释\n",
    "    # line1 = \"这是第一行\"\n",
    "    # line2 = \"这是第二行\"\n",
    "    # line3 = \"这是第三行\"\n",
    "    pass"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5db59686",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 2. 自动生成文档\n",
    "def calculate_compound_interest(principal, rate, time, compound_frequency=1):\n",
    "    \"\"\"\n",
    "    计算复利\n",
    "    \n",
    "    使用复利公式计算投资的最终价值：\n",
    "    A = P(1 + r/n)^(nt)\n",
    "    \n",
    "    Args:\n",
    "        principal (float): 本金金额\n",
    "        rate (float): 年利率（小数形式，如0.05表示5%）\n",
    "        time (float): 投资时间（年）\n",
    "        compound_frequency (int, optional): 每年复利次数. Defaults to 1.\n",
    "    \n",
    "    Returns:\n",
    "        float: 最终金额\n",
    "    \n",
    "    Example:\n",
    "        >>> calculate_compound_interest(1000, 0.05, 10, 12)\n",
    "        1643.6194649900157\n",
    "    \n",
    "    Note:\n",
    "        利率应该以小数形式输入（例如，5%应该输入为0.05）\n",
    "    \"\"\"\n",
    "    amount = principal * (1 + rate / compound_frequency) ** (compound_frequency * time)\n",
    "    return amount"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d3da9fa2",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 3. 注释模板\n",
    "class ProjectTemplate:\n",
    "    \"\"\"\n",
    "    项目模板类\n",
    "    \n",
    "    Author: 开发者姓名\n",
    "    Date: 2024-10-01\n",
    "    Version: 1.0.0\n",
    "    \n",
    "    Description:\n",
    "        这个类提供了项目开发的基础模板，包含常用的方法和属性。\n",
    "    \n",
    "    Dependencies:\n",
    "        - Python 3.8+\n",
    "        - requests\n",
    "        - json\n",
    "    \n",
    "    Usage:\n",
    "        template = ProjectTemplate()\n",
    "        result = template.process_data(data)\n",
    "    \"\"\"\n",
    "    \n",
    "    def __init__(self):\n",
    "        \"\"\"\n",
    "        初始化模板\n",
    "        \n",
    "        初始化所有必要的属性和配置\n",
    "        \"\"\"\n",
    "        self.version = \"1.0.0\"\n",
    "        self.author = \"开发者姓名\"\n",
    "        self.created_date = \"2024-10-01\"\n",
    "    \n",
    "    def process_data(self, data):\n",
    "        \"\"\"\n",
    "        处理数据的主要方法\n",
    "        \n",
    "        Args:\n",
    "            data: 需要处理的数据\n",
    "        \n",
    "        Returns:\n",
    "            处理后的数据\n",
    "        \n",
    "        Raises:\n",
    "            ValueError: 当数据格式不正确时\n",
    "            TypeError: 当数据类型不匹配时\n",
    "        \n",
    "        Todo:\n",
    "            - 添加数据验证\n",
    "            - 优化处理性能\n",
    "            - 添加日志记录\n",
    "        \"\"\"\n",
    "        # 实现数据处理逻辑\n",
    "        pass"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fb64ef8e",
   "metadata": {},
   "source": [
    "## 7. 实际应用示例"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "360ccf2b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Web应用注释示例\n",
    "\n",
    "from flask import Flask, request, jsonify\n",
    "from datetime import datetime\n",
    "import logging\n",
    "\n",
    "# 配置日志\n",
    "logging.basicConfig(level=logging.INFO)\n",
    "logger = logging.getLogger(__name__)\n",
    "\n",
    "app = Flask(__name__)\n",
    "\n",
    "# 全局配置\n",
    "MAX_USERS_PER_REQUEST = 100  # 单次请求最大用户数限制\n",
    "RATE_LIMIT_WINDOW = 3600     # 限流时间窗口（秒）\n",
    "\n",
    "@app.route('/api/users', methods=['GET'])\n",
    "def get_users():\n",
    "    \"\"\"\n",
    "    获取用户列表API\n",
    "    \n",
    "    支持分页和过滤功能，返回用户基本信息。\n",
    "    \n",
    "    Query Parameters:\n",
    "        page (int): 页码，从1开始，默认为1\n",
    "        limit (int): 每页数量，最大100，默认为20\n",
    "        status (str): 用户状态过滤，可选值：active, inactive, all\n",
    "        search (str): 搜索关键词，支持用户名和邮箱模糊搜索\n",
    "    \n",
    "    Returns:\n",
    "        JSON: 包含用户列表和分页信息的响应\n",
    "        {\n",
    "            \"users\": [...],\n",
    "            \"pagination\": {\n",
    "                \"page\": 1,\n",
    "                \"limit\": 20,\n",
    "                \"total\": 150,\n",
    "                \"pages\": 8\n",
    "            }\n",
    "        }\n",
    "    \n",
    "    Status Codes:\n",
    "        200: 成功返回用户列表\n",
    "        400: 请求参数错误\n",
    "        500: 服务器内部错误\n",
    "    \"\"\"\n",
    "    try:\n",
    "        # 获取查询参数\n",
    "        page = int(request.args.get('page', 1))\n",
    "        limit = min(int(request.args.get('limit', 20)), MAX_USERS_PER_REQUEST)\n",
    "        status = request.args.get('status', 'all')\n",
    "        search = request.args.get('search', '')\n",
    "        \n",
    "        # 记录API调用日志\n",
    "        logger.info(f\"获取用户列表: page={page}, limit={limit}, status={status}\")\n",
    "        \n",
    "        # 构建查询条件\n",
    "        filters = {}\n",
    "        if status != 'all':\n",
    "            filters['status'] = status\n",
    "        if search:\n",
    "            filters['search'] = search\n",
    "        \n",
    "        # 查询数据库（示例）\n",
    "        users, total_count = query_users(\n",
    "            page=page, \n",
    "            limit=limit, \n",
    "            filters=filters\n",
    "        )\n",
    "        \n",
    "        # 构建响应数据\n",
    "        response_data = {\n",
    "            'users': [format_user_data(user) for user in users],\n",
    "            'pagination': {\n",
    "                'page': page,\n",
    "                'limit': limit,\n",
    "                'total': total_count,\n",
    "                'pages': (total_count + limit - 1) // limit  # 向上取整\n",
    "            }\n",
    "        }\n",
    "        \n",
    "        return jsonify(response_data), 200\n",
    "        \n",
    "    except ValueError as e:\n",
    "        # 参数格式错误\n",
    "        logger.warning(f\"参数错误: {str(e)}\")\n",
    "        return jsonify({'error': '请求参数格式错误'}), 400\n",
    "        \n",
    "    except Exception as e:\n",
    "        # 服务器内部错误\n",
    "        logger.error(f\"获取用户列表失败: {str(e)}\")\n",
    "        return jsonify({'error': '服务器内部错误'}), 500"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "85c44f04",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 2. 数据分析注释示例\n",
    "\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.linear_model import LinearRegression\n",
    "from sklearn.metrics import mean_squared_error, r2_score\n",
    "\n",
    "def analyze_sales_data(data_file):\n",
    "    \"\"\"\n",
    "    销售数据分析函数\n",
    "    \n",
    "    对销售数据进行探索性分析和预测建模\n",
    "    \n",
    "    Args:\n",
    "        data_file (str): 数据文件路径\n",
    "    \n",
    "    Returns:\n",
    "        dict: 包含分析结果的字典\n",
    "    \"\"\"\n",
    "    \n",
    "    # 1. 数据加载和初步检查\n",
    "    print(\"=== 数据加载阶段 ===\")\n",
    "    df = pd.read_csv(data_file)\n",
    "    print(f\"数据形状: {df.shape}\")\n",
    "    print(f\"列名: {list(df.columns)}\")\n",
    "    \n",
    "    # 检查缺失值\n",
    "    missing_data = df.isnull().sum()\n",
    "    print(f\"缺失值统计:\\n{missing_data[missing_data > 0]}\")\n",
    "    \n",
    "    # 2. 数据清洗\n",
    "    print(\"\\n=== 数据清洗阶段 ===\")\n",
    "    \n",
    "    # 处理缺失值：销售额用中位数填充，分类变量用众数填充\n",
    "    numeric_columns = df.select_dtypes(include=[np.number]).columns\n",
    "    categorical_columns = df.select_dtypes(exclude=[np.number]).columns\n",
    "    \n",
    "    for col in numeric_columns:\n",
    "        if df[col].isnull().sum() > 0:\n",
    "            median_value = df[col].median()\n",
    "            df[col].fillna(median_value, inplace=True)\n",
    "            print(f\"列 {col} 的缺失值已用中位数 {median_value} 填充\")\n",
    "    \n",
    "    for col in categorical_columns:\n",
    "        if df[col].isnull().sum() > 0:\n",
    "            mode_value = df[col].mode()[0]\n",
    "            df[col].fillna(mode_value, inplace=True)\n",
    "            print(f\"列 {col} 的缺失值已用众数 {mode_value} 填充\")\n",
    "    \n",
    "    # 3. 探索性数据分析\n",
    "    print(\"\\n=== 探索性数据分析 ===\")\n",
    "    \n",
    "    # 基本统计信息\n",
    "    print(\"数值型变量统计摘要:\")\n",
    "    print(df.describe())\n",
    "    \n",
    "    # 销售趋势分析（假设有日期列）\n",
    "    if 'date' in df.columns:\n",
    "        df['date'] = pd.to_datetime(df['date'])\n",
    "        monthly_sales = df.groupby(df['date'].dt.to_period('M'))['sales'].sum()\n",
    "        \n",
    "        plt.figure(figsize=(12, 6))\n",
    "        monthly_sales.plot(kind='line', marker='o')\n",
    "        plt.title('月度销售趋势')\n",
    "        plt.xlabel('月份')\n",
    "        plt.ylabel('销售额')\n",
    "        plt.grid(True, alpha=0.3)\n",
    "        plt.xticks(rotation=45)\n",
    "        plt.tight_layout()\n",
    "        plt.show()\n",
    "    \n",
    "    # 4. 特征工程\n",
    "    print(\"\\n=== 特征工程阶段 ===\")\n",
    "    \n",
    "    # 创建新特征：销售额分类\n",
    "    df['sales_category'] = pd.cut(\n",
    "        df['sales'], \n",
    "        bins=[0, 1000, 5000, 10000, float('inf')],\n",
    "        labels=['低', '中', '高', '极高']\n",
    "    )\n",
    "    \n",
    "    # 创建季节特征（如果有日期）\n",
    "    if 'date' in df.columns:\n",
    "        df['season'] = df['date'].dt.month.map({\n",
    "            12: '冬', 1: '冬', 2: '冬',\n",
    "            3: '春', 4: '春', 5: '春',\n",
    "            6: '夏', 7: '夏', 8: '夏',\n",
    "            9: '秋', 10: '秋', 11: '秋'\n",
    "        })\n",
    "    \n",
    "    # 5. 预测建模（简单线性回归示例）\n",
    "    print(\"\\n=== 预测建模阶段 ===\")\n",
    "    \n",
    "    # 选择特征和目标变量\n",
    "    feature_columns = [col for col in numeric_columns if col != 'sales']\n",
    "    if len(feature_columns) > 0:\n",
    "        X = df[feature_columns]\n",
    "        y = df['sales']\n",
    "        \n",
    "        # 划分训练集和测试集\n",
    "        X_train, X_test, y_train, y_test = train_test_split(\n",
    "            X, y, test_size=0.2, random_state=42\n",
    "        )\n",
    "        \n",
    "        # 训练模型\n",
    "        model = LinearRegression()\n",
    "        model.fit(X_train, y_train)\n",
    "        \n",
    "        # 预测和评估\n",
    "        y_pred = model.predict(X_test)\n",
    "        mse = mean_squared_error(y_test, y_pred)\n",
    "        r2 = r2_score(y_test, y_pred)\n",
    "        \n",
    "        print(f\"模型评估结果:\")\n",
    "        print(f\"均方误差 (MSE): {mse:.2f}\")\n",
    "        print(f\"决定系数 (R²): {r2:.3f}\")\n",
    "        \n",
    "        # 特征重要性\n",
    "        feature_importance = pd.DataFrame({\n",
    "            'feature': feature_columns,\n",
    "            'coefficient': model.coef_\n",
    "        }).sort_values('coefficient', key=abs, ascending=False)\n",
    "        \n",
    "        print(f\"\\n特征重要性:\")\n",
    "        print(feature_importance)\n",
    "    \n",
    "    # 6. 结果汇总\n",
    "    results = {\n",
    "        'data_shape': df.shape,\n",
    "        'missing_values_handled': True,\n",
    "        'features_created': ['sales_category'],\n",
    "        'model_performance': {\n",
    "            'mse': mse if 'mse' in locals() else None,\n",
    "            'r2': r2 if 'r2' in locals() else None\n",
    "        }\n",
    "    }\n",
    "    \n",
    "    if 'date' in df.columns:\n",
    "        results['features_created'].append('season')\n",
    "    \n",
    "    return results\n",
    "\n",
    "# 使用示例\n",
    "if __name__ == \"__main__\":\n",
    "    # 注意：这里需要实际的数据文件\n",
    "    # results = analyze_sales_data('sales_data.csv')\n",
    "    # print(f\"\\n分析完成，结果: {results}\")\n",
    "    pass"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "279c9244",
   "metadata": {},
   "source": [
    "## 8. 注释的常见错误"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8163de45",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. 过度注释\n",
    "\n",
    "# 错误示例：过度注释\n",
    "def calculate_sum(a, b):\n",
    "    # 定义变量a\n",
    "    # 定义变量b\n",
    "    # 计算a和b的和\n",
    "    result = a + b  # 将a和b相加并赋值给result\n",
    "    # 返回结果\n",
    "    return result  # 返回result变量的值\n",
    "\n",
    "# 正确示例：适度注释\n",
    "def calculate_weighted_average(values, weights):\n",
    "    \"\"\"计算加权平均值\"\"\"\n",
    "    if len(values) != len(weights):\n",
    "        raise ValueError(\"值和权重的数量必须相等\")\n",
    "    \n",
    "    # 使用向量化操作提高性能\n",
    "    weighted_sum = sum(v * w for v, w in zip(values, weights))\n",
    "    total_weight = sum(weights)\n",
    "    \n",
    "    return weighted_sum / total_weight if total_weight != 0 else 0"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bb66e48f",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 2. 过时的注释\n",
    "\n",
    "# 错误示例：注释与代码不一致\n",
    "def process_user_data(users):\n",
    "    # 过滤掉年龄小于18的用户（注释过时了）\n",
    "    filtered_users = [user for user in users if user['age'] >= 21]  # 实际是21岁\n",
    "    return filtered_users\n",
    "\n",
    "# 正确示例：保持注释与代码同步\n",
    "def process_user_data(users, min_age=21):\n",
    "    \"\"\"\n",
    "    过滤用户数据\n",
    "    \n",
    "    Args:\n",
    "        users: 用户列表\n",
    "        min_age: 最小年龄限制，默认21岁\n",
    "    \"\"\"\n",
    "    filtered_users = [user for user in users if user['age'] >= min_age]\n",
    "    return filtered_users"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "94806b02",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 3. 无意义的注释\n",
    "\n",
    "# 错误示例：无意义的注释\n",
    "i = 0  # 设置i为0\n",
    "while i < 10:  # 当i小于10时循环\n",
    "    print(i)  # 打印i\n",
    "    i += 1  # i增加1\n",
    "\n",
    "# 正确示例：有意义的注释\n",
    "retry_count = 0\n",
    "MAX_RETRIES = 10\n",
    "\n",
    "while retry_count < MAX_RETRIES:\n",
    "    try:\n",
    "        # 尝试连接数据库\n",
    "        connection = establish_database_connection()\n",
    "        break\n",
    "    except ConnectionError:\n",
    "        retry_count += 1\n",
    "        # 指数退避策略：每次重试间隔时间翻倍\n",
    "        time.sleep(2 ** retry_count)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4a97ee7d",
   "metadata": {},
   "source": [
    "## 9. 练习"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bc5d2e41",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. 为简单函数添加注释\n",
    "\n",
    "def fibonacci(n):\n",
    "    # TODO: 为这个函数添加适当的注释\n",
    "    if n <= 1:\n",
    "        return n\n",
    "    else:\n",
    "        return fibonacci(n-1) + fibonacci(n-2)\n",
    "\n",
    "# 参考答案\n",
    "def fibonacci(n):\n",
    "    \"\"\"\n",
    "    计算斐波那契数列的第n项\n",
    "    \n",
    "    使用递归方法计算，时间复杂度为O(2^n)\n",
    "    \n",
    "    Args:\n",
    "        n (int): 要计算的项数（从0开始）\n",
    "    \n",
    "    Returns:\n",
    "        int: 斐波那契数列的第n项\n",
    "    \n",
    "    Example:\n",
    "        >>> fibonacci(5)\n",
    "        5\n",
    "        >>> fibonacci(10)\n",
    "        55\n",
    "    \"\"\"\n",
    "    if n <= 1:\n",
    "        return n\n",
    "    else:\n",
    "        return fibonacci(n-1) + fibonacci(n-2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5b0e98af",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 2. 改进注释质量\n",
    "\n",
    "def calc(x, y, op):\n",
    "    # 计算\n",
    "    if op == '+':\n",
    "        return x + y  # 加法\n",
    "    elif op == '-':\n",
    "        return x - y  # 减法\n",
    "    elif op == '*':\n",
    "        return x * y  # 乘法\n",
    "    elif op == '/':\n",
    "        return x / y  # 除法\n",
    "\n",
    "# 改进后的版本\n",
    "def calculate(operand1, operand2, operator):\n",
    "    \"\"\"\n",
    "    执行基本数学运算\n",
    "    \"\"\""
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "base",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
